<!-- 发布宠物页面 -->
<template>
    <div class="post-newpet-container">
        <div class="petinfo-form-container">
            <el-form ref="ruleFormRef" :model="ruleForm" label-width="70px">
                <el-form-item label="宠物名字">
                    <el-input v-model="ruleForm.petName" placeholder="请输入宠物的名字" />
                </el-form-item>
                <el-form-item label="品种">
                    <el-input v-model="ruleForm.breed" placeholder="请输入宠物的品种" />
                </el-form-item>
                <el-form-item label="类别" :error="speciesError">
                    <el-input v-model="ruleForm.species" placeholder="请输入宠物的类别:猫或狗或其他" @input="handleSpeciesInput" />
                    <template #error>
                        <span v-if="speciesError">{{ speciesError }}</span>
                    </template>
                </el-form-item>
                <el-form-item label="年龄">
                    <el-input v-model="ruleForm.age" placeholder="请输入宠物的年龄" />
                </el-form-item>
                <el-form-item label="押金">
                    <el-input v-model="ruleForm.deposit" placeholder="请输入宠物的押金" />
                </el-form-item>
                <el-form-item label="地区">
                    <el-input v-model="ruleForm.region" placeholder="请输入地区" />
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="ruleForm.gender">
                        <el-radio value="男">男</el-radio>
                        <el-radio value="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="疫苗接种">
                    <el-radio-group v-model="ruleForm.vaccinated">
                        <el-radio value="1">已接种</el-radio>
                        <el-radio value="0">未接种</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="健康情况">
                    <el-radio-group v-model="ruleForm.healthy">
                        <el-radio value="1">健康</el-radio>
                        <el-radio value="0">患病</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="ruleForm.details" placeholder="介绍宠物的情况" />
                </el-form-item>
            </el-form>
        </div>
        <div class="petinfo-form-container">
            <h2>上传图片</h2>
            <el-upload class="upload-demo" ref="uploadRef" drag action="#" :on-change="handlePictureChange"
                :show-file-list="false" :auto-upload="false">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">点击上传，或将图片拖到此处</div>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过50MB</div>
            </el-upload>
            <div class="preview-container" v-if="imageUrl">
                <img :src="imageUrl" alt="预览图" class="preview-image" />
                <el-button @click="removeImage" type="danger" size="small">删除图片</el-button>
            </div>
        </div>
        <button @click="submitForm" class="btn" title="点击发布">发布</button>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useUserStore } from "@/stores/user"
import { publishPetInfo, postImageAPI } from "@/api/pet"
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const user = userStore.user;

const publisher_id = user.user_id
console.log("发布者id:", publisher_id)

// 错误信息响应式变量
const speciesError = ref('');

const handleSpeciesInput = (val: string) => {
//   console.log(val)  
  const validValues = ['猫', '狗', '其他'];

  //判断输入值val是否存在：猫狗其他   
  const isInvalid = !validValues.includes(val) && val !== ''; // 允许空值（未输入时不报错）

  if (isInvalid) {
    speciesError.value = '请输入猫、狗或其他'; // 显示错误提示
    ruleForm.species = ''; // 清空非法输入
  } else {
    speciesError.value = ''; // 清除错误提示
    ruleForm.species = val; // 允许合法输入
  }
};

// 使用 ref 创建模板引用
const ruleFormRef = ref(null)
const uploadRef = ref(null)

const ruleForm = reactive({
    petName: '',
    breed: '',
    species: "", // 类别
    gender: '',
    vaccinated: '', // 疫苗接种情况，1表示已经接种疫苗，0表示未接种疫苗
    healthy: '', // 健康情况，1表示健康，0表示患病
    office: '0',
    region: '',
    age: '',
    deposit: "",//押金
    adopted: '0',//收养状态：0未被收养
    imageUrls: [], // 图片路径，初始化为空数组
    details: "",
    publisher_id: publisher_id, // 发布者 ID
})


const imageUrl = ref('')// 存储上传图片的URL
const uploadFile = ref(null)// 存储上传的文件对象
// 处理图片上传
const handlePictureChange = async (file, fileList) => {
    const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
    const isLt50M = file.raw.size / 1024 / 1024 < 10

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt50M) {
        ElMessage.error('上传图片大小不能超过 10MB!')
        return false
    }

    try {
        // 创建FormData对象，用于上传文件
        const formData = new FormData()
        formData.append('file', file.raw)

        // 调用上传图片的接口
        const res = await postImageAPI(formData)
        console.log(res.url)

        // 处理接口返回的数据，将url存储在ruleForm.imageUrls数组中
        ruleForm.imageUrls.push(res.url)

        imageUrl.value = res.url
        uploadFile.value = file.raw
    } catch (error) {
        ElMessage.error('图片上传失败')
        console.error(error)
    }
}

// 删除已上传的图片
const removeImage = () => {
    imageUrl.value = ''
    uploadFile.value = null
    // 从数组中移除对应的图片URL
    const index = ruleForm.imageUrls.indexOf(imageUrl.value)
    if (index > -1) {
        ruleForm.imageUrls.splice(index, 1)
    }
}

// 发布接口
const submitForm = async () => {
    // 检查ruleForm中的值是否有空值
    for (const key in ruleForm) {
        if (ruleForm[key] === '') {
            ElMessage({
                message: '宠物信息不完善，无法发布',
                type: 'warning',
            });
            return;
        }
    }

    try {
        // 调用发布宠物接口
        const res = await publishPetInfo(ruleForm);
        console.log(res.message);
        if (res.message === "宠物发布成功") {
            ElMessage({
                message: '宠物发布成功',
                type: 'success',
            });
            // 发布成功后重置表单
            resetForm()
        }
    } catch (error) {
        ElMessage({
            message: '宠物发布失败',
            type: 'error',
        });
        console.error(error);
    }
};

// 重置表单
const resetForm = () => {
    for (const key in ruleForm) {
        ruleForm[key] = ''
    }
    ruleForm.publisher_id = publisher_id
    imageUrl.value = ''
    uploadFile.value = null
    ruleForm.imageUrls = [] // 重置时将imageUrls设为空数组
}

console.log(ruleForm)
</script>

<style lang="scss" scoped>
.post-newpet-container {
    width: 970px;
    margin-left: 30px;
    // border: 1px solid black;
    background: #fafafa;
    position: relative;
}

.title {
    margin: 10px;
}

.petinfo-form-container {
    width: 400px;
    padding: 10px;
    margin-left: 70px;
    margin-top: 50px;
    // border: 1px solid black;
    display: inline-block;
    vertical-align: top;
}

.upload-demo {
    margin-top: 20px;
}

.preview-container {
    margin-top: 20px;
}

.preview-image {
    max-width: 100%;
    max-height: 200px;
    margin-bottom: 10px;
}

.btn {
    position: absolute;
    bottom: 30px;
    right: 100px;
    background: #055B5C;
    width: 100px;
    height: 30px;
    border: none;
    color: white;
    transition: all 0.3s ease;
}

.btn:hover {
    background: #087d7e;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    cursor: pointer;
}
</style>